/**
 * Created by Administrator on 2025/5/8.
 * */
#include "MainController.h"

BaseObject *createMainController() {
    return new MainController();
}

/**
 * 设计方案
 * 1. TCP Server用于控制step是否增加，有一个单独的TCP Client发送指令控制；
 * 2. 在onCompute的每一步：将step通过TCP Client发送给模块列表，模块收到后，根据step做相应操作
 *    首先更新参数，如升级完成，更新误差为新值，然后打印日志：模块替换：误差：10%，消息：正常工作 / 模型升级成功
 * 3. 每个模块均有TCP Server来接收step并进行相应的处理
 * 4. step值的定义、误差值定义等在每个项目的MainController子项目的global.h中，所有其他子系统在第一个模块的构造函数初始化本
 *    子系统中对应参数。向MainController的TCP Server发送请求获取Json格式字符串
 * 5. 各子系统Log发送到MainController子系统TCP Server进行统一记录，日志以子系统名+冒号+空格开头
 * @param p
 */

void destroyMainController(BaseObject *p) {
    SAFE_DELETE(p);
}

MainController::MainController(){
    std::cout << "启动中心控制器" << std::endl;
    // 启动时间步主题
    pub = zmq::socket_t(ctx, zmq::socket_type::pub);
    pub.bind(topicAddr.c_str());
    std::cout << "MainController bind to " << topicAddr << "..." << std::endl;
    // AI控制相关服务端
    std::cout << "AI控制相关服务端初始化" << std::endl;
    zrSockAis = zmq::socket_t(ctx, zmq::socket_type::rep);
    zrSockAis.bind(zrAddrAis);
    std::thread thd(&MainController::serveAisZR, this);
    thd.detach();
}

MainController::~MainController() {
}

void MainController::serveAisZR() {
    while (true) {
        std::cout << "等待AI相关控制命令" << std::endl;
        // 处理CFAR控制命令
        zmq::message_t command;
        try {
            zrSockAis.recv(command, zmq::recv_flags::none);
        } catch (const zmq::error_t& e) {
            std::cerr << "ZMQ error: " << e.what() << std::endl;
        }
        uint8_t *pData = reinterpret_cast<uint8_t*>(command.data());
        int cmdId;
        memcpy(&cmdId, &pData[0], sizeof(int));
        int cmdLen = 0;
        memcpy(&cmdLen, &pData[sizeof(int)], sizeof(int));
        std::string msg(reinterpret_cast<char*>(&pData[2*sizeof(int)]), cmdLen);
        std::cout << "### 消息：" << msg << "; ????????????" << std::endl;
        if (1 == cmdId) {
            std::cout << "" << std::endl;
        }
        // 发送确认
        int ackId = 0, ackLen;
        std::string ackMsg = "MainController接收到消息";
        ackLen = ackMsg.length();
        zmq::message_t ack(sizeof(int)*2 + ackLen);
        uint8_t *pAckData = reinterpret_cast<uint8_t*>(ack.data());
        memcpy(&pAckData[0], &ackId, sizeof(int));
        memcpy(&pAckData[sizeof(int)], &ackLen, sizeof(int));
        memcpy(&pAckData[2*sizeof(int)], ackMsg.data(), ackLen);
        zrSockAis.send(ack, zmq::send_flags::none);
    }
}

/* 如果使用了DDS_Reader或者DDS_Writer，则对应的input或者output前64个字节为DataFormat head首部 */
void MainController::onCompute(buffer_table_t *input, buffer_table_t *output) {
    step++;
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    zmq::message_t topic(topicName);
    zmq::message_t content(sizeof(int));
    memcpy(content.data(), &step, sizeof(int));
    if (!pub.send(topic, zmq::send_flags::sndmore) || !pub.send(content, zmq::send_flags::none)) {
        std::cerr << "Publisher: Faile to send frame" << std::endl;
    }
    std::cout << "将时间节点(step=" << step << ")发布到MainController主题..." << std::endl;
}













// void MainController::onCompute(buffer_table_t *input, buffer_table_t *output) {
//     step++;
//     range += dr;
//     theta += da;
//     phi += da;
//     std::this_thread::sleep_for(std::chrono::milliseconds(3000));
//     demo();
// }

int MainController::startup() {
    step = 0;
    return 0;
}

int MainController::demo() {
    dataSource();
    traditionAlgorithm();
    aiNodeInfer();
    aiE2EInfer();
    dataCenter();
    aiPCTrain();
    aiCFARTrain();
    aiE2ETrain();
    return 0;
}

int MainController::dataSource() {
    if (C1 == step ) {
        std::cout << "启动DataSource.DataGenerator" << std::endl;
        std::cout << "DataSource: 目标回波[" << range << ", "<< velocity << ", " << theta << ", " << phi << ", drone]" << std::endl;
        return 0;
    }
    if (step>=C2 && step<=C3) {
        std::cout << "DataSource: 目标回波[" << range << ", "<< velocity << ", " << theta << ", " << phi << ", drone]" << std::endl;
        return 0;
    }
    return 0;
}

int MainController::dataCenter() {
    if (step>=C2 && step<=C3) {
        std::cout << "DataCenter: 保存数据并更新数据集: [" << range << ", "<< velocity << ", " << theta << ", " << phi << ", drone]" << std::endl;
        return 0;
    }
    if (C4 == step) {
        std::cout <<"DataCenter: 通知AIPCNet、AICFARNet、AIE2ENet开始训练" << std::endl;
        return 0;
    }
    return 0;
}

int MainController::traditionAlgorithm() {
    float scale = 0.0;
    if (step <= CEND) {
        scale = 1.0 + errorRate0;
        std::cout << "TraditionAlgorithm: 误差: " << errorRate0 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone" << std::endl;
        return 0;
    }
    return 0;
}

int MainController::aiNodeInfer() {
    float scale = 0.0;
    if (step>=0 && step<=C7) { // 刚上线时
        scale = 1.0 + errorRate11;
        std::cout << "AINodeInfer: 误差: " << errorRate11 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone" << std::endl;
    } else if (step>=C8 && step<=C15) {
        scale = 1.0 + errorRate21;
        std::cout << "AINodeInfer: 误差: "<< errorRate21 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone" << std::endl;
    } else if (step>=C15 && step<=CEND) {
        scale = 1.0 + errorRate31;
        std::cout << "AINodeInfer: 误差: "<< errorRate31 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone" << std::endl;
    }
    if (C7 == step) {
        std::cout << "AIPC: 模型升级" << std::endl;
        std::cout << "AICFAR: 模型升级" << std::endl;
        return 0;
    }
    if (C10 == step) {
        std::cout << "AINodeInfer: 检测到与传统算法差异，通知AINodeTrain进行微调训练" << std::endl;
    }
    if (C14 == step) {
        std::cout << "AIPC: 模型升级" << std::endl;
        std::cout << "AICFAR: 模型升级" << std::endl;
        return 0;
    }
    return 0;
}

int MainController::aiE2EInfer() {
    float scale = 0.0;
    if (step>=0 && step<=C7) { // 刚上线时
        scale = 1.0 + errorRate12;
        std::cout << "AIE2EInfer: 误差: " << errorRate12 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone" << std::endl;
    } else if (step>=C8 && step<=C19) {
        scale = 1.0 + errorRate22;
        std::cout << "AIE2EInfer: 误差: " << errorRate22 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone]" << std::endl;
    } else if (step>=C20 && step<=C24) {
        scale = 1.0 + errorRate32;
        std::cout << "AIE2EInfer: 误差: " << errorRate32 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone]" << std::endl;
    } else if (step>=C25 && step<=C29) {
        scale = 1.0 + errorRate42;
        std::cout << "AIE2EInfer: 误差: " << errorRate42 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone]" << std::endl;
    } else if (step>=C30 && step<=CEND) {
        scale = 1.0 + errorRate52;
        std::cout << "AIE2EInfer: 误差: " << errorRate52 << "\n\t目标1 " << range*scale << ", "<< velocity*scale << ", " << theta*scale << ", " << phi*scale << ", drone]" << std::endl;
    }
    if (C7 == step) {
        std::cout << "AIE2E: 模型升级" << std::endl;
        return 0;
    }
    if (C16 == step) {
        std::cout << "AIE2EInfer: 检测到与传统算法差异，通知AIE2ETrain进行微调训练" << std::endl;
        return 0;
    }
    if (C19 == step) {
        std::cout << "AIE2E: 模型升级" << std::endl;
        return 0;
    }
    if (C21 == step) {
        std::cout << "AIE2EInfer: 未能正确识别系统添加的虚拟真值目标，通知AIE2ETrain进行微调训练" << std::endl;
        return 0;
    }
    if (C24 == step) {
        std::cout << "AIE2E: 模型升级" << std::endl;
        return 0;
    }
    if (C29 == step) {
        std::cout << "AIE2E: 模型升级" << std::endl;
        return 0;
    }
    return 0;
}

int MainController::aiPCTrain() {
    if (C4 == step) {
        std::cout << "AIPCNet: 启动脉压模型训练" << std::endl;
        return 0;
    }
    if (C6 == step) {
        std::cout << "AIPCNet: 脉压模型训练结束通知AIPC模块升级" << std::endl;
        return 0;
    }
    // 第1次与传统算法差异
    if (C11 == step) {
        std::cout << "AIPCNet: 启动脉压模型训练" << std::endl;
        return 0;
    }
    if (C13 == step) {
        std::cout << "AIPCNet: 脉压模型训练结束通知AIPC模块升级" << std::endl;
        return 0;
    }
    return 0;
}

int MainController::aiCFARTrain() {
    if (C4 == step) {
        std::cout << "AICFARNet: 启动恒虚警模型训练" << std::endl;
        return 0;
    }
    if (C6 == step) {
        std::cout << "AICFARNet: 恒虚警模型训练结束通知AICFAR模块升级" << std::endl;
        return 0;
    }
    // 第1次与传统算法差异
    if (C11 == step) {
        std::cout << "AICFARNet: 启动恒虚警模型训练" << std::endl;
        return 0;
    }
    if (C14 == step) {
        std::cout << "AICFARNet: 恒虚警模型训练结束通知AICFAR模块升级" << std::endl;
        return 0;
    }
    return 0;
}

int MainController::aiE2ETrain() {
    if (C4 == step) {
        std::cout << "AIE2ENet: 启动端到端模型训练" << std::endl;
        return 0;
    }
    if (C6 == step) {
        std::cout << "AIE2ENet: 端到端模型训练结束通知AIE2E模块升级" << std::endl;
        return 0;
    }
    // 第1次与传统算法误差过大微调
    if (C17 == step) {
        std::cout << "AIE2ENet: 启动端到端模型训练" << std::endl;
        return 0;
    }
    if (C18 == step) {
        std::cout << "AIE2ENet: 端到端模型训练结束通知AIE2E模块升级" << std::endl;
        return 0;
    }
    if (C26 == step) {
        std::cout << "AIE2ETrain: 自监督算法复原和预测误差过大，通知AIE2ENet进行微调训练" << std::endl; 
        return 0;
    }
    if (C27 == step) {
        std::cout << "AIE2ENet: 启动自监督算法微调训练" << std::endl;
        return 0;
    }
    if (C28 == step) {
        std::cout << "AIE2ENet: 自监督算法微调训练结束，通知AIE2E模块升级" << std::endl;
    }
    return 0;
}
